package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.injector.methods.SelectCount;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    FileStorageService fileStorageService;


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 注入上传文件需要的数据    阿里云OSS
     */
    //文件名后缀     阿里云桶里面文件夹的层级
    @Value("${file.oss.prefix}")
    String prefix;
    //站点
    @Value("${file.oss.web-site}")
    String webSite;



    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"缺少参数");
        }

        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //判断上传的文件格式    获取文件后缀名
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR,"文件格式有误");
        }

        // 2 上传到oss
        //上传对象
        String fileId = null;
        //获取随机名字  将随机名字中的 -  替换成  空字符串
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //  获取上传的数据以  最后 一个  .  切割的最后一部分  (数据包括 . )
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            //获取上传对象           文件名前缀       随机名字+上传的文件名后缀           输入流
            fileId = fileStorageService.store(prefix,uuid+substring,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }

        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());

        //保存到数据库
        save(wmMaterial);

        //前端显示   站点+上传对象
        wmMaterial.setUrl(webSite+fileId);


        //返回结果
        return ResponseResult.okResult(wmMaterial);


    }


    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }





    /**
     * 查询所有数据
     * @param
     * @return
     */
    @Override
    public PageResponseResult findList(WmMaterialDTO dto) {
        //校验参数   分页
        dto.checkParam();
        //业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection , dto.getIsCollection());
        }
        //当前用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        wrapper.eq(WmMaterial::getUserId , user.getId());
        //时间但需
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> materialIPage = page(page, wrapper);

        //获取参数
        List<WmMaterial> materialList = materialIPage.getRecords();

        for (WmMaterial wmMaterial : materialList) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }

        //封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), materialIPage.getTotal());
        pageResponseResult.setData(materialList);
        return pageResponseResult;
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult del_picture(Integer id) {
        //校验参数
        if (id == null ){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断当前id的数据是否被引用
        WmMaterial material = getById(id);
        if (material == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer integer = wmNewsMaterialMapper.selectCount(wrapper);
        if (integer>0){
            //表示改图片被别的表引用了  不能删除
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该图片不能删除");
        }

        //删除图片
        removeById(id);

        //删除oss的图片
        fileStorageService.delete(material.getUrl());

        return ResponseResult.okResult();

    }


    /**
     * 收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id , Short type) {
        //判断参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }

        //获取当前登录用户的id
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //这张图片的作者的id   和  当前登录的用户的id 判断是否是用一个人
        if(!wmMaterial.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }

        //根据传递的状态更改状态
        wmMaterial.setIsCollection(type);
        //修改
        updateById(wmMaterial);
        //返回值
        return ResponseResult.okResult();

    }


}






